﻿<%@ WebHandler Language="C#" Class="YPContainerMaterialHandler" %>

using System;
using System.Web;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Linq;
using BusinessRule.Business;
using System.Data;
using Newtonsoft.Json;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.Collections;
using BusinessRule.DTO;
using System.Web.SessionState;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using DatabaseAccess.DBUtility;
using TransferInsiteDataBusiness;

public class YPContainerMaterialHandler : IHttpHandler, IRequiresSessionState
{
    private YPContainerBusiness YpContainer = new YPContainerBusiness();
    private uLMSCommonIBusiness m_CommonObj = uMESBusinessFactory.instance.GetuLMSCommonObject();
    private uLMSContainerIBusiness m_ContainerObj = uMESBusinessFactory.instance.GetuLMSContainerObject();
    private TransferInsiteDataBusiness.TransferInsiteDataBusiness transferObj = new TransferInsiteDataBusiness.TransferInsiteDataBusiness();

    CurrentUserInfo m_UserInfo;
    public void ProcessRequest(HttpContext context)
    {
        var action = context.Request.Form["action"].ToString();
        switch (action)
        {
            case "searchData":
                SearchData(context);
                break;
            case "searchDataDetail":
                SearchDataDetail(context);
                break;
            case "searchMaterialChildData":
                SearchMaterialChildData(context);
                break;
            case "confirmData":
                ConfirmData(context);
                break;
            case "changeWorkflow":
                ChangeWorkflow(context);
                break;
            case "changeContainerQty":
                ChangeContainerQty(context);
                break;
            default:
                break;
        }

    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    /// <summary>
    /// 查询获取列表
    /// </summary>
    /// <param name="context"></param>
    public void SearchData(HttpContext context)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
        para.Add("CurrentPageIndex", context.Request.Form["pageNumber"].ToString());//页码
        para.Add("PageSize", context.Request.Form["pageSize"].ToString());//每页页数
        para.Add("ContainerName", context.Request.Form["containerName"].ToString());
        para.Add("ScanContainerName", context.Request.Form["scanContainerName"].ToString());
        if (!string.IsNullOrWhiteSpace(para["ScanContainerName"]))
        {
            para["ScanContainerName"] = m_CommonObj.ContainerScan(para["ScanContainerName"]);
        }
        para.Add("MfgorderName", context.Request.Form["scanMfgorderName"].ToString());
        String searchType = context.Request.Form["pageType"].ToString();
        string processNode = context.Request.Form["processNode"].ToString();
        para.Add("FactoryID", m_UserInfo.FactoryID.ToString());
        switch (processNode)//type:1工艺确认，2温度填写，3检验确认,4到料确认
        {
            case "工艺确认":
                para.Add("CheckTechnique", m_UserInfo.EmployeeName.ToString());
                para.Add("WorkflowStepName", "工艺确认");
                break;
            case "温度确认":
                para.Add("WorkflowStepName", "温度确认");
                para.Add("IsselfMfg", "0");
                break;
            case "物料检验":
                //para.Add("Sequence", "3");
                para.Add("WorkflowStepName", "物料检验");
                break;
            case "到料确认":
                para.Add("WorkflowStepName", "到料确认");
                break;
            default:
                break;
        }

        uMESProcessResult result = YpContainer.GetContainerMaterialData(para);

        context.Response.ContentType = "text/plain";
        context.Response.Write(JsonConvert.SerializeObject(result));

    }

    /// <summary>
    /// 查询批次明细
    /// </summary>
    /// <param name="context"></param>
    public void SearchDataDetail(HttpContext context)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("ContainerType", context.Request.Form["containerType"].ToString());
        para.Add("ProductBatchReal", context.Request.Form["productBatchReal"].ToString()); //件号批次号单件单卡为Togetherflag，其他则为containername

        DataTable result = YpContainer.GetContainerMaterialDataDetail(para);

        context.Response.ContentType = "text/plain";
        context.Response.Write(JsonConvert.SerializeObject(result));

    }

    /// <summary>
    /// 查询批次子序号的领料信息
    /// </summary>
    /// <param name="context"></param>
    public void SearchMaterialChildData(HttpContext context)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("ContainerID", context.Request.Form["containerID"].ToString());

        DataTable result = YpContainer.GetChildMaterialInfo(para["ContainerID"]);

        context.Response.ContentType = "text/plain";
        context.Response.Write(JsonConvert.SerializeObject(result));

    }

    /// <summary>
    /// 数据提交
    /// </summary>
    /// <param name="context"></param>
    public void ConfirmData(HttpContext context)
    {
        var param = context.Request.Form;
        DataTable mainData = JsonConvert.DeserializeObject<DataTable>(param["selectMainData"].ToString());
        DataTable selectData = JsonConvert.DeserializeObject<DataTable>(param["selectData"].ToString());
        //var pageType = param["pageType"].ToString();//type:1工艺确认，2温度填写，3检验确认,4到料确认
        string processNode = context.Request.Form["processNode"].ToString();
        var strInfo = ""; var res = false; m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];

        var daServerHost = new ServerHostInfo();
        daServerHost.UserName = m_UserInfo.APIUserName;
        daServerHost.Password = m_UserInfo.APIPassword;
        if (m_UserInfo.FactoryCode != "608")
        {
            return;
        }
        foreach (DataRow selectRow in selectData.Rows)
        {
            if (processNode == "工艺确认")//mainData.Rows[0]["WORKFLOWSTEPNAME"].ToString() == "工艺确认"
            {
                if (mainData.Rows[0]["ISLASTSTEP"].ToString() == "1" || !string.IsNullOrWhiteSpace(selectRow["OrgContainerName"].ToString()))//直接到在制情况：最后一序;补出来的卡
                {
                    res = YpContainer.MoveMfgWorkFlow(selectRow["containername"].ToString(), mainData.Rows[0]["CONTAINERLEVELNAME"].ToString(), selectRow["MFGWORKFLOWID"].ToString(),
                        selectRow["BEGINSTEP"].ToString(), m_UserInfo, ref strInfo);
                }
                else
                {
                    if (selectRow["isselfmfg"].ToString() == "0" && m_UserInfo.FactoryCode == "608")//如果为叶片分厂、领料批次才验证
                    {
                        var temp = m_CommonObj.GetTableInfo("YPTitaniumMaterial", "MATERIALTRADEMARK", mainData.Rows[0]["MATERIALTRADEMARK"].ToString());
                        if (temp.Rows.Count == 0)
                        {
                            res = false;
                            strInfo = "批次" + selectRow["ContainerName"].ToString() + "未维护钛合金";
                            break;//结束
                        }
                        if (temp.Rows[0]["ISTITANIUM"].ToString() == "0")//不是钛合金材料,继续移动
                        {
                            res = m_ContainerObj.ContainerMoveStd(daServerHost, selectRow["ContainerName"].ToString(), m_UserInfo.EmployeeName, ref strInfo);
                            if (!res)
                            {
                                break;//结束
                            }
                        }
                    }
                    res = m_ContainerObj.ContainerMoveStd(daServerHost, selectRow["ContainerName"].ToString(), m_UserInfo.EmployeeName, ref strInfo);
                    //领料情况下,判断是否是钛合金材料
                    //if (selectRow["isselfmfg"].ToString() == "0" && res)
                    //{
                    //    var temp = m_CommonObj.GetTableInfo("YPTitaniumMaterial", "MATERIALTRADEMARK", mainData.Rows[0]["MATERIALTRADEMARK"].ToString());
                    //    if (temp.Rows.Count == 0 || temp.Rows[0]["ISTITANIUM"].ToString() == "0")//不是钛合金材料,继续移动
                    //    {
                    //        res = m_ContainerObj.ContainerMoveStd(daServerHost, selectRow["ContainerName"].ToString(), m_UserInfo.EmployeeName, ref strInfo);
                    //    }
                    //}
                }
                //记录工艺确认的人和时间
                var exuteEntity = new ExcuteEntity("containercurrentinfo", ExcuteEntity.ExcuteTypeEnum.update);
                var excuteFileds = new List<FieldEntity>() {new FieldEntity("techniqueemployeeid", m_UserInfo.EmployeeID, FieldEntity.FieldTypeEnum.Str),
                                                                          new FieldEntity("techniquedate",DateTime.Now, FieldEntity.FieldTypeEnum.DateTime )};

                //如果是补出来的卡，此时将到料确认人信息继承
                if (!string.IsNullOrWhiteSpace(selectRow["OrgContainerName"].ToString()))
                {
                    var orgConDt = m_CommonObj.GetTableInfo("containercurrentinfo", "containername", selectRow["OrgContainerName"].ToString());

                    excuteFileds.Add(new FieldEntity("MATERIALEMPLOYEEID", orgConDt.Rows[0]["MATERIALEMPLOYEEID"].ToString(), FieldEntity.FieldTypeEnum.Str));
                    excuteFileds.Add(new FieldEntity("materialdate", DateTime.Now, FieldEntity.FieldTypeEnum.DateTime));

                }
                exuteEntity.ExcuteFileds = excuteFileds;
                exuteEntity.WhereFileds = new List<FieldEntity>() { new FieldEntity("containerid", selectRow["Containerid"].ToString(), FieldEntity.FieldTypeEnum.Str) };

                DatabaseHelper.ExecuteDataByEntity(exuteEntity);
            }
            else if (processNode == "温度确认")//温度填写
            {
                res = m_ContainerObj.ContainerMoveStd(daServerHost, selectRow["ContainerName"].ToString(), m_UserInfo.EmployeeName, ref strInfo);
                //记录温度确认人和时间
                if (res)
                {
                    var exuteEntity = new ExcuteEntity("containercurrentinfo", ExcuteEntity.ExcuteTypeEnum.update);
                    var excuteFileds = new List<FieldEntity>() {new FieldEntity("yptemperaempid", m_UserInfo.EmployeeID, FieldEntity.FieldTypeEnum.Str),
                                                                         new FieldEntity("yptemperaconfirmdate",DateTime.Now, FieldEntity.FieldTypeEnum.DateTime )};
                    exuteEntity.ExcuteFileds = excuteFileds;
                    exuteEntity.WhereFileds = new List<FieldEntity>() { new FieldEntity("containerid", selectRow["Containerid"].ToString(), FieldEntity.FieldTypeEnum.Str) };

                    DatabaseHelper.ExecuteDataByEntity(exuteEntity);
                }
            }
            else if (processNode == "物料检验")//检验确认
            {
                //移动 
                if (mainData.Rows[0]["ISLASTSTEP"].ToString() == "1")
                {
                    res = YpContainer.MoveMfgWorkFlow(selectRow["containername"].ToString(), mainData.Rows[0]["CONTAINERLEVELNAME"].ToString(), selectRow["MFGWORKFLOWID"].ToString(),
                           selectRow["BEGINSTEP"].ToString(), m_UserInfo, ref strInfo);
                }
                else
                {
                    res = m_ContainerObj.ContainerMoveStd(daServerHost, selectRow["ContainerName"].ToString(), m_UserInfo.EmployeeName, ref strInfo);
                }
                if (res)
                {
                    //更改段批号
                    var ypContainerNo = param["ypContainerNo"].ToString();
                    if (ypContainerNo != selectRow["ypContainerNo"].ToString())
                        YpContainer.ChangeYpContainerNo(selectRow["Containerid"].ToString(), ypContainerNo);
                    //记录检验人和时间
                    var exuteEntity = new ExcuteEntity("containercurrentinfo", ExcuteEntity.ExcuteTypeEnum.update);
                    var excuteFileds = new List<FieldEntity>() {new FieldEntity("checkconfirmempid", m_UserInfo.EmployeeID, FieldEntity.FieldTypeEnum.Str),
                                                                         new FieldEntity("checkconfirmdate",DateTime.Now, FieldEntity.FieldTypeEnum.DateTime )};
                    exuteEntity.ExcuteFileds = excuteFileds;
                    exuteEntity.WhereFileds = new List<FieldEntity>() { new FieldEntity("containerid", selectRow["Containerid"].ToString(), FieldEntity.FieldTypeEnum.Str) };

                    DatabaseHelper.ExecuteDataByEntity(exuteEntity);

                }
            }
            else if (processNode == "到料确认")//到料确认
            {
                //移动 
                if (mainData.Rows[0]["ISLASTSTEP"].ToString() == "1")
                {
                    res = YpContainer.MoveMfgWorkFlow(selectRow["containername"].ToString(), mainData.Rows[0]["CONTAINERLEVELNAME"].ToString(), selectRow["MFGWORKFLOWID"].ToString(),
                           selectRow["BEGINSTEP"].ToString(), m_UserInfo, ref strInfo);
                }
                else
                {
                    res = m_ContainerObj.ContainerMoveStd(daServerHost, selectRow["ContainerName"].ToString(), m_UserInfo.EmployeeName, ref strInfo);
                }

                //记录到料确认的人和时间
                //记录检验人和时间
                var exuteEntity = new ExcuteEntity("containercurrentinfo", ExcuteEntity.ExcuteTypeEnum.update);
                var excuteFileds = new List<FieldEntity>() {new FieldEntity("MATERIALEMPLOYEEID", m_UserInfo.EmployeeID, FieldEntity.FieldTypeEnum.Str),
                                                                         new FieldEntity("materialdate",DateTime.Now, FieldEntity.FieldTypeEnum.DateTime )};
                exuteEntity.ExcuteFileds = excuteFileds;
                exuteEntity.WhereFileds = new List<FieldEntity>() { new FieldEntity("containerid", selectRow["Containerid"].ToString(), FieldEntity.FieldTypeEnum.Str) };

                DatabaseHelper.ExecuteDataByEntity(exuteEntity);
            }
        }

        //更新工序信息
        transferObj.UpdateSpecInfo();

        var result = new uMESProcessResult();
        result.Result = res;
        result.Message = strInfo;

        context.Response.ContentType = "text/plain";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }


    /// <summary>
    /// 工艺修改
    /// </summary>
    /// <param name="context"></param>
    public void ChangeWorkflow(HttpContext context)
    {
        var param = context.Request.Form;
        DataTable selectData = JsonConvert.DeserializeObject<DataTable>(param["selectData"].ToString());

        context.Session["PopupData"] = selectData;

        var result = new uMESProcessResult();
        result.Result = true;
        result.Message = "session保存成功";
        context.Response.ContentType = "text/plain";
        context.Response.Write(JsonConvert.SerializeObject(result));

    }

    /// <summary>
    /// 数量更改，实到数确认
    /// </summary>
    /// <param name="context"></param>
    public void ChangeContainerQty(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        var param = context.Request.Form;
        DataTable selectData = JsonConvert.DeserializeObject<DataTable>(param["selectData"].ToString());
        var changeQty = param["changeQty"].ToString();
        m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
        var result = new uMESProcessResult();
        result.Result = false;

        var tempDt = m_CommonObj.GetTableInfo("qtyadjustreason", "qtyadjustreasonname", "实到数变更");
        if (tempDt.Rows.Count == 0)
        {
            result.Message = "请联系管理员维护qtyadjustreason对象的 “实到数变更” 原因";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }

        foreach (DataRow selectRow in selectData.Rows)
        {
            //往数量调整表里存值
            var para = new Dictionary<String, String>();
            var intQty = int.Parse(changeQty) - int.Parse(selectRow["qty"].ToString());
            para["containerCheckInfoID"] = "";
            para["containerID"] = selectRow["containerID"].ToString();
            para["changeQtyType"] = "1";
            para["qty"] = changeQty;
            para["reasonID"] = tempDt.Rows[0]["qtyadjustreasonid"].ToString();
            para["containerStepWorkReportID"] = "";
            para["scrapSourceType"] = "7"; //到料确认，实到数变更
            para["EmployeeID"] = m_UserInfo.EmployeeID.ToString();
            para["WorkflowstepID"] = "";
            m_ContainerObj.AddCheckQtyChangeRecord(para);
            //更改批次数量
            m_ContainerObj.ChangeContainerQty(selectRow["containerID"].ToString(), intQty);
        }
        result.Result = true;
        result.Message = "实到数确认成功";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 保存勾选的数据
    /// </summary>
    /// <param name="context"></param>
    public void SaveData(HttpContext context)
    {
        CurrentUserInfo m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["tableData"].ToString());
        List<Dictionary<string, string>> dicList = new List<Dictionary<string, string>>();


    }

    #region "确认数据"

    #endregion


}